<template>
	<el-card shadow="hover">
		<template #header>信息修改</template>
		<section class="user">
			<el-upload
				:show-file-list="false"
				:on-success="handleAvatarSuccess"
				:http-request="uploadApi"
			>
				<el-avatar
					v-if="userAdmin.userInfo?.headerImg || userForm.headerImg"
					:size="120"
					:src="image"
				/>
				<el-avatar v-else :size="120">
					{{ userAdmin.userInfo.nickName?.split('')[0] }}
				</el-avatar>
			</el-upload>
			<el-form inline :model="userForm" label-width="120px" class="user-form">
				<el-form-item label="昵称">
					<el-input v-model="userForm.nickName" />
				</el-form-item>
				<el-form-item label="手机号">
					<el-input v-model="userForm.phone" />
				</el-form-item>
				<el-form-item label="邮箱">
					<el-input v-model="userForm.email" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="setUserInfo">保存</el-button>
				</el-form-item>
			</el-form>
		</section>
	</el-card>
	<el-divider border-style="dashed" />
	<el-card shadow="hover">
		<template #header>密码修改</template>
		<el-form inline :model="pwd" label-width="120px">
			<el-form-item label="原始密码">
				<el-input v-model="pwd.password" />
			</el-form-item>
			<el-form-item label="新密码">
				<el-input v-model="pwd.newPassword" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="changePwd">保存</el-button>
			</el-form-item>
		</el-form>
	</el-card>
</template>

<script setup>
import { computed, reactive } from 'vue'
import { changePwdApi, setUserInfoApi, uploadApi } from '@/api/api.js'
import useAdminStore from '@/store/index.js'
import { ElMessage } from 'element-plus'

const image = computed(
	() =>
		import.meta.env.VITE_APP_IP + userForm.headerImg ||
		userAdmin.userInfo.headerImg,
)
const userAdmin = useAdminStore()

const userForm = reactive({ nickName: '', phone: '', email: '', headerImg: '' })
const pwd = reactive({
	password: '',
	newPassword: '',
})

Object.assign(userForm, JSON.parse(JSON.stringify(userAdmin.userInfo)))
const handleAvatarSuccess = (res) => {
	userForm.headerImg = res.file.url
}

const setUserInfo = async () => {
	try {
		await setUserInfoApi(userForm)
		ElMessage.success('修改成功')
		window.location.reload()
	} catch (err) {
		console.log(err)
	}
}

const changePwd = async () => {
	try {
		await changePwdApi(pwd)
		ElMessage.success('修改成功，请重新登陆')
		sessionStorage.clear()
		window.location.reload()
	} catch (err) {
		console.log(err)
	}
}
</script>

<style scoped>
.user {
	padding: 20px;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}
.user-form {
	margin-top: 40px;
}
</style>
